#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author:jiangying
# @Lastupdatedate:2019/01/25


'''eof
name:对外担保金额(总)比月均申报收入总额
code:EC05_ExtGuarAmtToTaxMonthlyIncomePro
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ,IC_DSJ,TX_CQ_DSJ
type:常用指标
dataSourceType:
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isfloat(x):
    try:
        if isinstance(float(x), float):
            if x in ['inf', 'infinity', 'INF', 'INFINITY', True, 'NAN', 'nan',
                     False, '-inf', '-INF', '-INFINITY', '-infinity', 'NaN', 'Nan']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def getTableEC(table_Name):
    try:
        data = EC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['ReportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def getTableIC(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def getTableTX(table_Name):
    '''
    获取表
    :param x:
    :return:
    '''
    try:
        ic_data = TX_CQ_DSJ['data'].get(table_Name)
        if ic_data in null_type_list:
            return None
        else:
            return ic_data if isinstance(ic_data, list) and len(ic_data) > 0 else [{}]
    except:
        return None

# 个人对外担保金额
def ICGuarantee():
    try:
        ICRGuaranteeSummary = getTableIC('ICRGuaranteeSummary')
        if ICRGuaranteeSummary is None:
            return None
        elif ICRGuaranteeSummary == [{}]:
            return 0.0
        else:
            if ICRGuaranteeSummary[0].get('reportNo') not in null_type_list \
                and isfloat(ICRGuaranteeSummary[0].get('amount')) \
                    and float(ICRGuaranteeSummary[0].get('amount')) >= 0:
                return float(ICRGuaranteeSummary[0].get('amount'))
            else:
                return None
    except:
        return None

#企业对外担保金额
def ECGuarantee():
    try:
        ECRSummaryGuarantee = getTableEC('ECRSummaryGuarantee')
        if ECRSummaryGuarantee is None:
            return None
        elif ECRSummaryGuarantee == [{}]:
            return 0.0
        else:
            flag = []
            bz_amt = 0
            dy_amt = 0
            zy_amt = 0
            for i in ECRSummaryGuarantee:

                if i.get('Guaranteetype') == u'保证汇总' and i.get('ReportNo') not in null_type_list:
                    bz_amt = i.get('GuaranteeAmount')
                    try:
                        bz_amt = float(bz_amt)
                    except:
                        bz_amt = None

                elif i.get('Guaranteetype') == u'抵押汇总' and i.get('ReportNo') not in null_type_list:
                    dy_amt = i.get('GuaranteeAmount')
                    try:
                        dy_amt = float(dy_amt)
                    except:
                        dy_amt = None

                elif i.get('Guaranteetype') == u'质押汇总' and i.get('ReportNo') not in null_type_list:
                    zy_amt = i.get('GuaranteeAmount')
                    try:
                        zy_amt = float(zy_amt)
                    except:
                        zy_amt = None

                else:
                    flag.append(None)

            if dy_amt == None and zy_amt == None and bz_amt == None:
                return None
            elif len(flag) == len(ECRSummaryGuarantee):
                return None
            else:
                if dy_amt is None:
                    dy_amt = 0
                if zy_amt is None:
                    zy_amt = 0
                if bz_amt is None:
                    bz_amt = 0
                return dy_amt + zy_amt + bz_amt
    except:
        return None

# 纳税人类型
def TaxerType():
    try:
        syptSwdjxx = getTableTX('syptSwdjxx')
        if syptSwdjxx == [{}] or syptSwdjxx is None:
            return None
        else:
            NSRZG_DM = syptSwdjxx[0].get('NSRZG_DM')
            if NSRZG_DM in null_type_list:
                return None
            elif NSRZG_DM not in null_type_list and NSRZG_DM in ['201', '202', '203', '204', '205']:
                return NSRZG_DM
            else:
                return u'其他'
    except:
        return None

# 一般纳税人
def ybnsr():
    try:
        syptZzsybnsr = getTableTX('syptZzsybnsr')
        if syptZzsybnsr is None or syptZzsybnsr == [{}]:
            return None
        else:
            # 可能存在统一年月 存在多次数据需要 用dict去重
            revenue = {}
            flag = []
            for i in syptZzsybnsr:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCont = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # 按适用税率计税销售额(ASYSLJSDNSJCYBJSE)
                    if isfloat(i.get('ASYSLJSDNSJCYBJSE')):
                        a1 = float(i.get('ASYSLJSDNSJCYBJSE'))
                    else:
                        a1 = 0
                        noneCont += 1
                    # “按简易办法计税销售额(AJYZSBFZSHWXSE)”
                    if isfloat(i.get('AJYZSBFZSHWXSE')):
                        a2 = float(i.get('AJYZSBFZSHWXSE'))
                    else:
                        a2 = 0
                        noneCont += 1
                    # 免、抵、退办法出口销售额(MDTBFCKHWXSE)
                    if isfloat(i.get('MDTBFCKHWXSE')):
                        a3 = float(i.get('MDTBFCKHWXSE'))
                    else:
                        a3 = 0
                        noneCont += 1
                    # 免税销售额(MSHWJLWXSE)
                    if isfloat(i.get('MSHWJLWXSE')):
                        a4 = float(i.get('MSHWJLWXSE'))
                    else:
                        a4 = 0
                        noneCont += 1
                    if noneCont == 4:
                        flag.append(None)
                    else:
                        # 存入每个月的收入
                        revenue.update({ND + YF: a1 + a2 + a3 + a4})
            if revenue == {} or len(flag) == len(syptZzsybnsr):
                return None
            else:
                return float(sum(list(revenue.values()))) / float(len(revenue))
    except:
        return None

# 小规模纳税人
def xgm():
    try:
        syptZzsxgm = getTableTX('syptZzsxgm')
        if syptZzsxgm is None or syptZzsxgm == [{}]:
            return None
        else:
            revenue = {}
            flag = []
            for i in syptZzsxgm:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCount = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # “应征增值税货物及劳务不含税销售额(YZZZSHWJLWBHSXSEBNBQ)”
                    if isfloat(i.get('YZZZSHWJLWBHSXSEBNBQ')):
                        a1 = float(i.get('YZZZSHWJLWBHSXSEBNBQ'))
                    else:
                        a1 = 0
                        noneCount += 1
                    # “销售、出租不动产不含税销售额(XSCZBDCBHSXSE)”
                    if isfloat(i.get('XSCZBDCBHSXSE')):
                        a2 = float(i.get('XSCZBDCBHSXSE'))
                    else:
                        a2 = 0
                        noneCount += 1
                    # “销售使用过的应税固定资产不含税销售额(XSSYGDYSGDZCBHSXSEBNBQ)”
                    if isfloat(i.get('XSSYGDYSGDZCBHSXSEBNBQ')):
                        a3 = float(i.get('XSSYGDYSGDZCBHSXSEBNBQ'))
                    else:
                        a3 = 0
                        noneCount += 1
                    # “免税货物及劳务销售额(MSHWJLWXSEBNBQ)”
                    if isfloat(i.get('MSHWJLWXSEBNBQ')):
                        a4 = float(i.get('MSHWJLWXSEBNBQ'))
                    else:
                        a4 = 0
                        noneCount += 1
                    # 出口免税货物销售额(CKMSHWXSEBNBQ)
                    if isfloat(i.get('CKMSHWXSEBNBQ')):
                        a5 = float(i.get('CKMSHWXSEBNBQ'))
                    else:
                        a5 = 0
                        noneCount += 1
                    # 字段都有问题
                    if noneCount == 5:
                        flag.append(None)
                    else:
                        revenue.update({ND + YF: a1 + a2 + a3 + a4 + a5})
                else:
                    flag.append(None)
            if revenue == {} or len(flag) == len(syptZzsxgm):
                return None
            else:
                return float(sum(list(revenue.values()))) / float(len(revenue))
    except:
        return None

# 月均申报收入总和
def MonthlyIncomeReportAmt():
    try:
        taxerType = TaxerType()
        # 一般纳税人
        if taxerType in ['201', '202', '203']:
            result = ybnsr()
            if result is not None:
                return round(result, 4)
            else:
                return None
        # 小规模
        elif taxerType in ['204', '205']:
            result = xgm()
            if result is not None:
                return round(result, 4)
            else:
                return None
        # 其他情况
        elif taxerType is None or taxerType == u'其他':
            syptZzsxgm = getTableTX('syptZzsxgm')
            syptZzsybnsr = getTableTX('syptZzsybnsr')
            # 二者均为空
            if (syptZzsybnsr is None or syptZzsybnsr == [{}]) and (syptZzsxgm is None or syptZzsxgm == [{}]):
                return None
            # 二者均不为空
            elif syptZzsxgm not in [None, [{}]] and syptZzsybnsr not in [None, [{}]]:
                # 取出小规模纳税人表 和 一般纳税人表中 缴税年度和月份进行比较
                ybnsr_list = []
                xgm_list = []

                for i in syptZzsxgm:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isfloat(d):
                        xgm_list.append(float(d))
                    else:
                        pass

                for i in syptZzsybnsr:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isfloat(d):
                        ybnsr_list.append(float(d))
                    else:
                        pass

                if ybnsr_list == [] and xgm_list == []:
                    return None
                elif ybnsr_list != [] and xgm_list != []:
                    if max(ybnsr_list) >= max(xgm_list):
                        result = ybnsr()
                        if result is not None:
                            return round(result, 4)
                        else:
                            return None
                    else:
                        result = xgm()
                        if result is not None:
                            return round(result, 4)
                        else:
                            return None
                elif ybnsr_list != [] and xgm_list == []:
                    result = ybnsr()
                    if result is not None:
                        return round(result, 4)
                    else:
                        return None
                elif ybnsr_list == [] and xgm_list != []:
                    result = xgm()
                    if result is not None:
                        return round(result, 4)
                    else:
                        return None
                else:
                    assert False
            # 一般纳税人表为空 小规模不为空 用小规模纳税表计算
            elif syptZzsybnsr in [None, [{}]] and syptZzsxgm not in [None, [{}]]:
                result = xgm()
                if result is not None:
                    return round(result, 4)
                else:
                    return None
            # 一般纳税人不为空 小规模为空 用一般纳税人表计算
            elif syptZzsybnsr not in [None, [{}]] and syptZzsxgm in [None, [{}]]:
                result = ybnsr()
                if result is not None:
                    return round(result, 4)
                else:
                    return None
        else:
            assert False
    except:
        return None


def EC05_ExtGuarAmtToTaxMonthlyIncomePro():
    Factor1 = ICGuarantee()
    Factor2 = ECGuarantee()
    Factor3 = MonthlyIncomeReportAmt()

    if Factor3 == 0 or Factor3 is None:
        return u'缺失值'
    elif Factor1 is None and Factor2 is None:
        return u'缺失值'
    else:
        if Factor1 is None:
            Factor1 = 0.0
        else:
            Factor1 = Factor1 / 10000.0
        if Factor2 is None:
            Factor2 = 0.0

        Factor3 = Factor3 / 10000.0

        result = (float(Factor1) + float(Factor2)) / float(Factor3)
        return round(result, 4)

result = EC05_ExtGuarAmtToTaxMonthlyIncomePro()

